package userws

import (
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
)

type websocketHolder struct {
	ws    *websocket.Conn
	chanx chan bool
}

var (
	upgrader = websocket.Upgrader{ReadBufferSize: 1024,
		WriteBufferSize: 1024}

	WebsockRepos = make(map[string]*websocketHolder)
)

func AcceptWebsocket(w http.ResponseWriter, r *http.Request) {
	var account = r.Header.Get("account")

	log.Println("accept a new user websocket, account:", account)

	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println(err)
		return
	}

	older, ok := WebsockRepos[account]
	if ok {
		log.Println("duplicate websocket, close old one")
		older.ws.Close()
		<-older.chanx
	}

	chanx := make(chan bool, 1)
	WebsockRepos[account] = &websocketHolder{ws, chanx}

	for {
		messageType, p, err := ws.ReadMessage()
		if err != nil {
			break
		}

		if messageType == websocket.TextMessage {
			log.Println("Receive user websocket message:", string(p))
		}
	}

	log.Println("User websocket Receive error:", err)
	ws.Close()
	chanx <- true
	close(chanx)
	delete(WebsockRepos, account)
}

func Send2WS(account string, jsonMsg []byte) error {
	var wsHolder, ok = WebsockRepos[account]
	if !ok {
		return fmt.Errorf("account not connect:%s", account)
	}

	log.Printf("Send2WS, account %s, msg:%s", account, jsonMsg)

	return wsHolder.ws.WriteMessage(websocket.TextMessage, jsonMsg)
}
